import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr


def send_email(sender, receiver, smtp_server, smtp_port, password, subject, content):
    
    # 创建邮件对象
    message = MIMEMultipart()
    message['From'] = formataddr(("1831996597@qq.com", sender))  # 发件人昵称+邮箱
    if isinstance(receiver, list):
        message['To'] = ",".join([formataddr(("zzllinxi@gmail.com", r)) for r in receiver])
    else:
        message['To'] = formataddr(("zzllinxi@gmail.com", receiver))
    message['Subject'] = Header(subject, 'utf-8')

    # 添加邮件正文
    message.attach(MIMEText(content, 'plain', 'utf-8'))

    try:
        # 连接SMTP服务器 (SSL方式)
        smtp_obj = smtplib.SMTP_SSL(smtp_server, smtp_port)
        smtp_obj.login(sender, password)  # 登录邮箱
        smtp_obj.sendmail(sender, receiver, message.as_string())  # 发送邮件
        print("邮件发送成功")

    except smtplib.SMTPException as e:
        print(f"邮件发送失败: {e}")
    finally:
        smtp_obj.quit()


if __name__ == "__main__":
    # 配置信息
    sender_email = "1831996597@qq.com"  # 你的邮箱
    receiver_email = ["zzllinxi@gmail.com"]  # 收件人邮箱
    smtp_server = "smtp.qq.com"
    smtp_port = 465
    password = "bvcqzdzrxhsfbeaa"  # 你的 QQ 邮箱授权码

    subject = "Python自动发送邮件测试"
    content = """
    这是一封通过Python程序自动发送的测试邮件。

    请不要回复此邮件。

    Best regards,
    Python自动发送程序
    """

    send_email(sender_email, receiver_email, smtp_server, smtp_port, password, subject, content)
